<template>
	<view class="cc-line-clamp-wrap"
		:style="[{'--fontSize': computeFontSize, '--color':color, '--height':computeHeight}]">
		<view :class="['cc-text-wrap', isExpanded?'expanded':'collapsed']">
			<slot></slot>
		</view>
		<view class="toggleButton" v-if="showToggle" @click="toggleExpand">
			{{isExpanded?expandedText:collapsedText}}
			<uni-icons color="#6c6c6c" :type="isExpanded?'up':'down'" size="12" />
		</view>
	</view>
</template>

<script>
	export default {
		name: "cc-line-clamp",

		props: {
			fontSize: {
				type: Number,
				default: 28
			},
			color: {
				type: String,
				default: '#333'
			},
			// 隐藏的高度
			truncatedHeight: {
				type: Number,
				default: 45
			},

		},

		computed: {
			computeFontSize() {
				return this.fontSize + 'rpx'
			},
			computeHeight() {
				return this.truncatedHeight + 'px'
			},
		},

		data() {
			return {
				isExpanded: true, // 展开状态
				showToggle: false, // 是否需要显示切换按钮（根据文本是否超长判断）
				textHeight: 0,
				collapsedText:"展开更多",
				expandedText:"收起内容",
			};
		},

		mounted() {
			this.$nextTick(() => {
				let query = uni.createSelectorQuery().in(this);
				// 获取所有文本在html中的高度
				query.select('.cc-text-wrap').boundingClientRect(res => {
					this.textHeight = res.height
					if (this.textHeight > this.truncatedHeight) {
						this.showToggle = true;
						this.isExpanded = false;
					}
				}).exec();
			});
		},

		methods: {
			toggleExpand() {
				this.isExpanded = !this.isExpanded;
			},
		}
	}
</script>

<style scoped lang="scss">
	.cc-line-clamp-wrap {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 10rpx;

		.cc-text-wrap {
			width: 100%;
			font-size: var(--fontSize);
			color: var(--color);
			-webkit-box-orient: vertical;
			/* 保证单词或长数字也能换行 */
			word-break: break-word;
			/* 设置行高，视觉更舒适 */
			line-height: 1.5;
		}

		.collapsed {
			display: -webkit-box;
			overflow: hidden;
			text-overflow: ellipsis;
			height: var(--height);
		}

		.expanded {
			display: block;
			overflow: visible;
			-webkit-line-clamp: unset;
		}

		.toggleButton {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #6c6c6c;
		}
	}
</style>